<?php
/**
 * 八爪鱼接口调用
 * 1、签名
 * 2、发送请求
 *
 * @author: cnx7 <zysafe@live.cn> 2016-04-05
 */
class Bzy_Lite
{
    private $appId;
    private $openId;
    private $masterKey;
    private $url;
    private $timestamp;
    public function __construct()
    {
        $this -> appId     = DI()->config->get("app.Bzy.appId");
        $this -> openId    = DI()->config->get("app.Bzy.openId");
        $this -> masterKey = DI()->config->get("app.Bzy.masterKey");
        $this -> url       = DI()->config->get("app.Bzy.url");
        $this -> timestamp = date("YmdHis");
    }

    /**
     * 获取赛程
     * @param $data
     * @param $action
     * @return mixed
     */
    public function getData($data,$action){
        $dataJson = json_encode($data);
        $baseData = base64_encode($dataJson);
        $sign = $this -> sgin($baseData);
        $postArray = [
            "appKey"=>$this -> appId,
            "timestamp"=> $this -> timestamp,
            "sign"=>$sign,
            "data"=>$baseData
        ];
        $postJson = json_encode($postArray);
        $ret = $this->send($postJson,$action);
        return $ret;
    }


    /**
     * 八爪鱼签名
     * @param $baseData
     * @return string
     */
    public function sgin($baseData){

        $testArray[] = $this -> appId;
        if($baseData!=null)
            $testArray[] = $baseData;
        $testArray[] = $this -> openId;
        $testArray[] = $this -> timestamp;
        sort($testArray);
        $str = "";
        foreach ($testArray as $v){
            $str .=$v;
        }
        $sign = sha1($str);
        return $sign;
    }

    /**
     * 发送请求
     * @param $postData
     * @param $action
     * @return mixed
     */
    public function send($postData,$action){

        $headers[] = 'Content-Type:application/json;charset=utf-8';
        $url = $this->url.$action;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}